package com.process.demo;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * package com.process
 * description:
 *
 * @author tree
 * @date 2019-05-30 10:34
 */
public class Process1Demo {
    static String bashPath = "/Users/xingyun/IdeaProjects/PrintArgs/target";
    static String outputPath = "/Users/xingyun/IdeaProjects/eclipselinkDemo/src/main/java/com/process/demo/process.out";
    static String errorPath = "/Users/xingyun/IdeaProjects/eclipselinkDemo/src/main/java/com/process/demo/error.out";

    public static void main(String[] args) throws IOException {
        System.err.println(JSON.toJSONString(System.getenv()));

        List<String> list = new ArrayList<>();
        list.add("java");
        list.add("-jar");
        list.add("PrintArgs-1.0-SNAPSHOT.jar");
        list.add("a");
        list.add("b");
        list.add("c");
        File outputFile = new File(outputPath);
        if(!outputFile.exists()){
            outputFile.createNewFile();
        }
        File errorFile = new File(errorPath);
        if(!errorFile.exists()){
            errorFile.createNewFile();
        }

        ProcessBuilder processBuilder = new ProcessBuilder(list);
        processBuilder.redirectInput(outputFile);
        processBuilder.redirectError(errorFile);
        processBuilder.directory(new File(bashPath));
        processBuilder.redirectErrorStream(true);

        try {
            Process process = processBuilder.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            System.out.println("exitCode = "+exitCode);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}
